package com.guli.coupon.service.impl;

import com.guli.common.utils.R;
import com.guli.common.vo.CouponVo;
import com.guli.coupon.entity.CouponEntity;
import com.guli.coupon.service.CouponService;
import jdk.nashorn.internal.ir.annotations.Reference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.Query;
import com.guli.coupon.dao.CouponSpuCategoryRelationDao;
import com.guli.coupon.entity.CouponSpuCategoryRelationEntity;
import com.guli.coupon.service.CouponSpuCategoryRelationService;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;


@Service("couponSpuCategoryRelationService")
public class CouponSpuCategoryRelationServiceImpl extends ServiceImpl<CouponSpuCategoryRelationDao, CouponSpuCategoryRelationEntity> implements CouponSpuCategoryRelationService {
    @Resource
    private CouponService couponService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CouponSpuCategoryRelationEntity> page = this.page(
                new Query<CouponSpuCategoryRelationEntity>().getPage(params),
                new QueryWrapper<CouponSpuCategoryRelationEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CouponVo> getCouponsRelateCategoryId(Long categoryId) {
        List<CouponSpuCategoryRelationEntity> list = this.baseMapper
                .selectList(new QueryWrapper<CouponSpuCategoryRelationEntity>().eq("category_id", categoryId));
        if (CollectionUtils.isEmpty(list)) {
            return Collections.emptyList();
        }
        List<Long> couponIds = list.stream().map(CouponSpuCategoryRelationEntity::getCouponId).collect(Collectors.toList());
        List<CouponEntity> couponEntities = couponService.getBaseMapper().selectBatchIds(couponIds);
        if (CollectionUtils.isEmpty(couponEntities)) {
            return Collections.emptyList();
        }
        List<CouponVo> couponVos = couponEntities.stream().map(coupon -> {
            CouponVo couponVo = new CouponVo();
            BeanUtils.copyProperties(coupon, couponVo);
            return couponVo;
        }).collect(Collectors.toList());
        return couponVos;
    }

}